<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :search.sync="search"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               :before-open="beforeOpen"
               :page="page"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.user_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="primary"
                   size="small"
                   plain
                   icon="el-icon-refresh"
                   @click="handleReset">密码重置
        </el-button>
      </template>
      <template slot-scope="{row}" slot="memberCount">
        <a class="el-link" style="color: #2d8cf0" @click="openMemberList(row.id)">{{ row.memberCount }}</a>
      </template>
      <template slot="menu" slot-scope="{row}">
        <el-button size="small"
                   v-if="[1].includes(row.status)"
                   type="text"
                   @click="handleAddMember(row)">添加会员
        </el-button>
        <el-button size="small"
                   type="text"
                   @click="handleOpenPayment(row)">提成明细
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="会员列表"
               append-to-body
               :visible.sync="membersBox"
               :before-close="handleMembersClose"
               width="80%">
      <avue-crud :option="membersOption"
                 :table-loading="loading"
                 :data="membersData"
                 :page="membersPage"
                 ref="crud"
                 @search-change="membersSearchChange"
                 @search-reset="membersSearchReset"
                 @selection-change="membersSelectionChange"
                 @size-change="membersSizeChange"
                 @on-load="membersOnLoad">
        <template slot="menuLeft">
          <el-input style="display: inline-block; width: 200px; margin-right: 10px" v-model="searchName" clearable placeholder="昵称、姓名、手机号"></el-input>
          <el-button type="primary"
                     size="small"
                     @click="handleSearch">搜 索
          </el-button>
        </template>
        <template slot-scope="{row}" slot="status">
          <el-tag v-if="row.status === 1" type="success">已支付</el-tag>
          <el-tag v-else-if="row.status === 0" type="danger">未支付</el-tag>
          <el-tag v-else-if="row.status === 2" type="danger">关闭</el-tag>
          <el-tooltip v-else-if="row.status === 3"
                      effect="dark"
                      :content="`退款时间: ${row.refundTime}  备注: ${row.refundRemark}`"
                      placement="top">
            <el-tag type="danger">已退款</el-tag>
          </el-tooltip>
        </template>
        <template slot="menu" slot-scope="{row}">
          <el-button size="small"
                     v-if="mode === 'add'"
                     type="text"
                     @click="handleAdd(row)">添加
          </el-button>
          <el-button size="small"
                     v-if="mode === 'view'"
                     type="text"
                     @click="handleRemove(row)">移除
          </el-button>
          <el-button
            icon="el-icon-info"
            type="text"
            size="small"
            @click.stop="handleToDetail(row)"
          >查看
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>
    <el-dialog title="提成列表"
               append-to-body
               :visible.sync="paymentBox"
               :before-close="handlePaymentClose"
               width="70%">
      <customer-service-payment v-if="paymentRow.id" :form="paymentRow"></customer-service-payment>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getUser,
  remove,
  update,
  add,
  grant,
  resetPassword
} from "@/api/system/user";
import {getRoleTree} from "@/api/system/role";
import {mapGetters} from "vuex";
import website from '@/config/website';
import {addMember, memberList, removeMember} from "../../api/merchant/customer_service";
import CustomerServicePayment from "../system/customer_service_payment";

const customerServiceRoleId = '1724430728262672386'
export default {
  components: {CustomerServicePayment},
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      searchName: '',
      form: {},
      search:{},
      customerServiceId: '',
      mode: '',
      roleBox: false,
      membersBox: false,
      paymentBox: false,
      paymentRow: {},
      membersSelectionList: [],
      membersOption: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 100,
        selection: false,
        refreshBtn: false,
        column: [
          {
            label: "昵称",
            prop: "nickname",
            rules: [{
              required: true,
              message: "请输入昵称",
              trigger: "blur"
            }]
          },
          {
            label: "姓名",
            prop: "name",
            rules: [{
              required: true,
              message: "请输入姓名",
              trigger: "blur"
            }]
          },
          {
            label: "头像",
            prop: "avatar",
            dataType: 'string',
            type: 'upload',
            span: 24,
            listType: 'picture-card',
            propsHttp: {
              res: 'data',
              url: 'link',
              name: 'originalName'
            },
            limit: 1,
            action: '/api/blade-resource/oss/endpoint/put-file'
          },
          {
            label: "手机",
            prop: "phone",
            rules: [{
              required: true,
              message: "请输入手机",
              trigger: "blur"
            }]
          },
          {
            label: "剩余餐次",
            prop: "effectivePackagesCount",
            display: false,
          },
          {
            label: "剩余单餐餐时",
            prop: "effectivePackagesSingleCount",
            display: false,
          },
          {
            label: "剩余多餐餐时",
            prop: "effectivePackagesNotSingleCount",
            display: false,
          },
        ]
      },
      membersData: [],
      loading: true,
      selectionList: [],
      query: {},
      page: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      membersPage: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      props: {
        label: "title",
        value: "key"
      },
      roleGrantList: [],
      roleTreeObj: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        column: [
          {
            label: "账号",
            prop: "account",
            search: true,
            rules: [{
              required: true,
              message: "请输入账号",
              trigger: "blur"
            }],
            span: website.tenantMode ? 12 : 24,
          },
          {
            label: '密码',
            prop: 'password',
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            rules: [{required: true, validator: validatePass, trigger: 'blur'}]
          },
          {
            label: '确认密码',
            prop: 'password2',
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            rules: [{required: true, validator: validatePass2, trigger: 'blur'}]
          },
          {
            label: "姓名",
            prop: "realName",
            search: true,
            rules: [{
              required: true,
              message: "请输入用户姓名",
              trigger: "blur"
            }]
          },
          {
            label: "手机号码",
            prop: "phone",
            rules: [{
              required: true,
              message: "请输入手机号码",
              trigger: "blur"
            }],
            overHidden: true
          },
          {
            label: "管理会员",
            prop: "memberCount",
            slot: true,
            display: false
          },
          {
            label: "累计收益",
            prop: "allIncome",
            display: false
          },
          {
            label: "本月收益",
            prop: "monthIncome",
            display: false
          },
          {
            label: "账号状态",
            prop: "statusName",
            hide: true,
            display: false
          }
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/blade-user/import-user"
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: true,
        delBtn: false,
        editBtn: true
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    handleMembersClose() {
      this.membersBox = false
      this.mode = ''
      this.customerServiceId = ''
      this.membersData = []
      this.membersPage.total = 0
      this.membersSelectionList = []
      this.onLoad(this.page)
    },
    handlePaymentClose() {
      this.paymentBox = false
      this.paymentRow = {}
      this.onLoad(this.page)
    },
    handleToDetail(row) {
      this.$router.push({path: `/memberDetail?id=${row.id}` })
    },
    handleAdd(row) {
      this.$confirm("确定添加会员给该客服管理?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return addMember(this.customerServiceId, row.id);
        })
        .then(() => {
          this.membersOnLoad(this.membersPage);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleRemove(row) {
      this.$confirm("确定将该会员从该客服管理下移除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeMember(row.id);
        })
        .then(() => {
          this.membersOnLoad(this.membersPage);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleAddMember(row) {
      this.customerServiceId = row.id
      this.mode = 'add'
      this.membersBox = true
      this.membersOnLoad(this.membersPage)
    },
    handleOpenPayment(row) {
      this.paymentBox = true
      this.paymentRow = row
    },
    handleSearch() {
      this.membersPage.currentPage = 1
      this.membersOnLoad(this.membersPage)
    },
    membersOnLoad(page, params = {}) {
      this.loading = true;
      if (this.mode === 'view') {
        params.customerServiceId = this.customerServiceId
      }
      if (this.searchName && this.searchName !== '') {
        params.searchName = this.searchName
      }
      memberList(page.currentPage, page.pageSize, params).then(res => {
        const data = res.data.data;
        this.membersPage.total = data.total;
        this.membersData = data.records;
        this.loading = false;
      });
    },
    openMemberList(id) {
      this.customerServiceId = id
      this.mode = 'view'
      this.membersBox = true
      this.membersOnLoad(this.membersPage)
    },
    membersSizeChange(pageSize) {
      this.membersPage.pageSize = pageSize;
    },
    membersSearchReset() {
      this.membersOnLoad(this.membersPage);
    },
    membersSearchChange(params, done) {
      this.membersPage.currentPage = 1;
      this.membersOnLoad(this.membersPage, params);
      done();
    },
    membersSelectionChange(list) {
      this.membersSelectionList = list;
    },
    submitRole() {
      const roleList = this.$refs.treeRole.getCheckedKeys().join(",");
      grant(this.ids, roleList).then(() => {
        this.roleBox = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.onLoad(this.page);
      });
    },
    rowSave(row, done, loading) {
      row.roleId = customerServiceRoleId
      row.name = row.account
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      row.roleId = customerServiceRoleId
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleReset() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择账号密码重置为123456?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return resetPassword(this.ids);
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getUser(this.form.id).then(res => {
          this.form = res.data.data;
          if(this.form.hasOwnProperty("roleId")){
            this.form.roleId = this.form.roleId.split(",");
          }
        });
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.roleId = customerServiceRoleId
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
      getRoleTree(this.form.tenantId).then(res => {
        const column = this.findObject(this.option.column, "roleId");
        column.dicData = res.data.data;
      });
    }
  }
};
</script>

<style>
</style>
